/**
 * search data source
 */
package org.iridium.allcomments.util;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author iridium
 * 
 */
public class DatabaseConn {
	private static String driver;
	private static String url;
	private static String uid;
	private static String pwd;

	static {
		try {
			DocumentBuilderFactory domFactory = DocumentBuilderFactory
					.newInstance();
			domFactory.setNamespaceAware(true);
			DocumentBuilder builder = domFactory.newDocumentBuilder();
			
			// use the abstract path temply, will change to
			String confFile = "C:\\Documents and Settings\\caoyi\\workspace\\allcomments\\src\\config\\dbconf.xml";
			confFile = "/home/iridium/workspace/eclipse351/allcomments/src/config/dbconf.xml";
			Document confDoc = builder.parse(new File(confFile));

			XPathFactory factory = XPathFactory.newInstance();
			XPath path = factory.newXPath();
			driver = (String) path.evaluate(
					"/dbconf/db[@active='true']/driver", confDoc,
					XPathConstants.STRING);
			url = (String) path.evaluate("/dbconf/db[@active='true']/url",
					confDoc, XPathConstants.STRING);
			uid = (String) path.evaluate("/dbconf/db[@active='true']/user",
					confDoc, XPathConstants.STRING);
			pwd = (String) path.evaluate("/dbconf/db[@active='true']/password",
					confDoc, XPathConstants.STRING);
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static synchronized Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url, uid, pwd);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

}
